﻿#region
using System;
using System.Linq;
using EdmxTransformer.Components;

#endregion

namespace EdmxTransformer
{
    public partial class EdmxSchema
    {
        public void RefreshSchema(EdmxSchema newSchema)
        {
            var entityToDict = Entity.ToDictionary(x => x.From, x => x.To);
            var entitySetDict = Entity.ToDictionary(x => x.From, x => x.Set);
            var propertyDict = Property.ToDictionary(x => x.EntityFrom + "." + x.From, x => x.To);
            var navigationDict = Navigation.ToDictionary(x => x.EntityFrom + "." + x.From, x => x.To);

            Property.Clear();
            Navigation.Clear();
            Entity.Clear();

            foreach (var entity in newSchema.Entity)
            {
                var entityRow = Entity.AddEntityRow(entity.From, entityToDict.Get(entity.From), entitySetDict.Get(entity.From));

                foreach (var property in entity.GetPropertyRows())
                    Property.AddPropertyRow(entityRow, property.From, propertyDict.Get(property.EntityFrom + "." + property.From));

                foreach (var navigation in entity.GetNavigationRows())
                    Navigation.AddNavigationRow(entityRow, navigation.From, navigationDict.Get(navigation.EntityFrom + "." + navigation.From), navigation.Relationship, navigation.FromRole, navigation.ToRole, navigation.IsMultiple);
            }
        }

        public string GetEntityName(string entityFrom, bool plural = false)
        {
            EntityRow row = Entity.FindByFrom(entityFrom);

            if (plural)
                return row.Set;
            else
                return row.To;
        }

        public string GetPropertyName(string entityFrom, string @from)
        {
            var row = Property.FindByEntityFromFrom(entityFrom, @from);

            return row.To;
        }

        public string GetNavigationName(string relationship, string fromRole, string toRole)
        {
            var row = Navigation.FindByRelationshipToRoleFromRole(relationship, toRole, fromRole);

            return row.To;
        }

        public partial class EntityRow : IRow
        {
        }

        public partial class PropertyRow : IRow
        {
        }

        public partial class NavigationRow : IRow
        {
        }

        public partial class PrefixRuleRow : IRule
        {
        }

        public partial class PostfixRuleRow : IRule
        {
        }
    }

    public interface IRow
    {
        string From { get; set; }
        string To { get; set; }
    }

    public interface IRule
    {
        string From { get; set; }
        string To { get; set; }
    }
}